const App = getApp();
const api = require('../../../../utils/api.js');
const util = require('../../../../utils/util.js');

// pages/buy/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true, //是否显示面板指示点
    autoplay: true, //是否自动切换
    interval: 3000, //自动切换时间间隔,3s
    duration: 1000, //  滑动动画时长1s

    //页面图片适配
    imgwidth: 0,
    imgheight: 0,
    imgwidth1: 0,
    imgheight1: 0,
    imgwidth2: 0,
    imgheight2: 0,
    windowWidth: wx.getSystemInfoSync().screenWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    actionSheetHidden: true,
    //设置页面显示按钮类型
    buttonType: 0,
   

    goods_id: '',
    pic_info: '',
    pic_detail_info: '',
    list: '',
    num: 1
  },

  /**
 * 生命周期函数--监听页面加载
 */
  //初始化数据加载
  onLoad: function (options) {

    console.log(" 商品详情 onLoad................................")
    console.log(options)
    console.log(" 商品详情 scene................................")
    console.log(options.scene)


    this.setData({
      //buttonType: options.buttonType,
      goods_id: options.goods_id,
    })



    /** 判断场景值，1044 为转发场景，包含shareTicket 参数 */
    if (options.scene == 1044) {
      wx.getShareInfo({
        shareTicket: options.shareTicket,
        success: function (res) {
          var encryptedData = res.encryptedData;
          var iv = res.iv;
        }
      })
    }


    //转发设withShareTicket为true
    /*wx.showShareMenu({
      withShareTicket: true
    }) */
    //this.getGoodsMsg()


    //目前需要转发的 页面 暂时这么实现：
    //获得app_token和安全码security_code
    var that = this;
    const data = {
      app_id: App.globalData.app_id,
      private_key: App.globalData.private_key,
    };

    api.getTokenAndCode({
      data,
      success: (res) => {
        if (res.data.rsp_code == 'succ') {
          App.globalData.app_token = res.data.data.app_token;
          App.globalData.security_code = res.data.data.security_code;

          that.getGoodsMsg();//加载商品详情页

        } else if (res.data.rsp_code == 'fail') {
          console.log(res.data.error_code)
          console.log(res.data.error_msg)
        }
      }
    })
    //// end 

  },


  getGoodsMsg() {
    const self = this;

    let data = {
      service: 'goods.psGoodsDetailFind',
      params: '{"goods_id":""}',
      url_type: 'goods',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    var jsons = JSON.parse(data.params);
    jsons["goods_id"] = self.data.goods_id;
    data.params = JSON.stringify(jsons);


    api.reqData({
      data,
      success: (res) => {
        console.log("------------加载商品详情页------------------------")
        console.log(res.data)

        var productList = res.data.data.list
        var product = productList[0]
        //计算返款金额，保留两位小数（避免0.0098888情况） 映射到参数ts_price上
        var returnMomeny = (product.market_price - product.discount_price).toFixed(2);
        product.ts_price = returnMomeny;

        //处理预售商品的预售时间
        console.log(product.valid_thru)
        if (product.valid_thru != null) {
          var time1 = new Date().Format(product.valid_thru)
          var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");
          if (time1 > time2) {
            this.setData({
              buttonType: 9,
            })
          }
        }

        //图片地址由https 改为 http
        var doc_url_list = res.data.data.doc_url

        var doc_url_key = Object.keys(doc_url_list)
        var pic_info = JSON.parse(res.data.data.list[0].pic_info);
        var pic_detail_info = JSON.parse(res.data.data.list[0].pic_detail_info);
        for (var i = 0; i < doc_url_key.length; i++) {
          //doc_url_list[doc_url_key[i]] = doc_url_list[doc_url_key[i]].replace("https", "http")
          //分离pic_detail_info和pic_info
          for (var x = 0; x < pic_info.length; x++) {
            if (pic_info[x].path_id == doc_url_key[i]) {
              pic_info[x] = doc_url_list[doc_url_key[i]].replace("https", "http")
            }
          }

          for (var y = 0; y < pic_detail_info.length; y++) {
            if (pic_detail_info[y].path_id == doc_url_key[i]) {
              pic_detail_info[y] = doc_url_list[doc_url_key[i]].replace("https", "http")
            }
          }
        }

        //这个得写法和格式 setData({........})
        console.log(res.data);
        self.setData({
          pic_info: pic_info,
          pic_detail_info: pic_detail_info,
          list: productList
        })
      },
    })
  },

  //页面弹出半透明窗口js
  modalTap: function (e) {
    if (App.globalData.hasLogin === false) {//需要登录

      wx.navigateTo({
        url: '/pages/login/login',
      })

    } else {
      //判断是否有库存_逍遥子_2018-1-20
      console.log(this.data.list[0].sale_qty);
      if (this.data.list[0].sale_qty == 0 || this.data.list[0].sale_qty == "") {
        wx.showModal({
          title: '温馨提示',
          content: '该商品已下架！',
          showCancel: false,
          success: function (res) {
            app.userSignOut();
          }
        })
      } else {
      //判断是否已经绑定默认门店
      const self = this;
      console.log(self.data.num);
      let data = {
        service: 'stores.consumer.favoriteStoreList',
        params: '{"consumer_id":"0bc323a0d01811e7ac35c39610748aaf","is_llm_stores":"Y"}',
        url_type: 'member',
        app_token: App.globalData.app_token,
        security_code: App.globalData.security_code
      }

      var json = JSON.parse(data.params);
      json.consumer_id = App.globalData.memberInfo.member_id;
      data.params = JSON.stringify(json);

      api.reqData({
        data,
        success: (res) => {
          //这个得写法和格式 setData({........})
          console.log(res.data);
          let mark = res.data.data.list.length;
          //let stores_id = ""
          let goods_id = this.data.goods_id
          //商品数量通过页面传值的方法传输
          App.globalData.num = this.data.num;

          if (mark == 0) {
            //商品数量通过页面传值的方法传输
            App.globalData.num = this.data.num;
            this.setData({
              actionSheetHidden: false
            })
          } else {
            console.log("@@@@@@@@@@@@@@@@@@@@@");
            console.log(this.data.num);
            let stores_id = res.data.data.list[0].stores_id;
            wx.navigateTo({
              url: '../../submitOrder/submitOrder?stores_id=' + stores_id + '&goods_id=' + goods_id,
            })
          }
        },
      })
      }
    }
  },

  actionSheetChange: function (e) {
    this.setData({
      actionSheetHidden: true
    })
  },

  //我的收藏，附近门店页面跳转   goodsType：0 精品自营  1 淘宝商品
  toshoplist: function () {
    //参数："consumer_id":"11432431"
    let goods_id = this.data.goods_id
    let consumer_id = App.globalData.memberInfo.member_id
    //为防止回退后还浮动页面跳转前隐藏
    this.setData({
      actionSheetHidden: true
    })

    wx.navigateTo({
      url: '../../shoplist/shoplist?consumer_id=' + consumer_id + '&goodsType=' + 0 + '&goods_id=' + goods_id
    })
  },
  tonearshoplist: function () {
    let goods_id = this.data.goods_id
    //为防止回退后还浮动页面跳转前隐藏
    this.setData({
      actionSheetHidden: true
    })
    wx.navigateTo({
      url: '../../nearshoplist/nearshoplist?goodsType=' + 0 + '&goods_id=' + goods_id
    })
  },

  //商品图片适配
  imageLoad: function (e) {
    var windowWidth = this.data.windowWidth;
    var $width = e.detail.width;    //获取图片真实宽度  
    var $height = e.detail.height;
    var ratio = $width / $height;   //图片的真实宽高比例  
    //设置图片显示宽度,适配的比例，
    var viewWidth = windowWidth;
    var viewHeight = viewWidth / ratio;    //计算的高度值     
    this.setData({
      imgwidth: viewWidth,
      imgheight: viewHeight
    })
  },

  imageLoad1: function (e) {
    var windowWidth = this.data.windowWidth;
    var $width = e.detail.width;    //获取图片真实宽度  
    var $height = e.detail.height;
    var ratio = $width / $height;   //图片的真实宽高比例  
    //设置图片显示宽度,适配的比例，
    var viewWidth = windowWidth;
    var viewHeight = viewWidth / ratio;    //计算的高度值     
    this.setData({
      imgwidth1: viewWidth,
      imgheight1: viewHeight
    })
  },

  imageLoad2: function (e) {
    var windowWidth = this.data.windowWidth;
    var $width = e.detail.width;    //获取图片真实宽度  
    var $height = e.detail.height;
    var ratio = $width / $height;   //图片的真实宽高比例  
    //设置图片显示宽度,适配的比例，
    var viewWidth = windowWidth * 0.2;
    var viewHeight = viewWidth / ratio;    //计算的高度值     
    this.setData({
      imgwidth2: viewWidth,
      imgheight2: viewHeight
    })
  },



  // 减少商品数量
  bindMinus: function () {
    let num = this.data.num
    if (num > 1) {
      num--
    } else {
      num = 1
    }
    this.setData({
      num: num
    })
  },

  //点击加号
  bindPlus: function () {
    let num = this.data.num
    let nummax = this.data.list[0].sale_qty
    num++
    if (num > nummax) {
      num = nummax,
        wx.showToast({
          title: '库存不足',
          duration: 2000
        })
    }
    this.setData({
      num: num
    })
  }, 



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */

  onReachBottom: function () {
999999
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {

    //转发设withShareTicket为true,可以二次转发
    wx.showShareMenu({
      withShareTicket: true
    })

    if (res.from === 'menu') {
      // 来自页面内转发按钮
      console.log(res.from)
      console.log(res.target)
    }

    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route

    console.log("三个参数>>>>>>>>>>>>>>>>>>>>>>>")
    console.log(pages)
    console.log(currentPage)
    console.log(url)
    console.log(currentPage.data.goods_id)



    //var desc = "领有惠实惠商品";
    var title = " ￥" + this.data.list[0].discount_price
      + " (返还￥" + this.data.list[0].ts_price + ") |" + this.data.list[0].title;

    return {
      title: title,
      //desc:desc,
      //path: "/" + url + '?goods_id=' + currentPage.data.goods_id,
      success: function (res) {

        // 转发成功
        console.log(res)
        console.log("KKKKKKKKKKKKKK   转发转发转发 success 111111111")

        var shareTickets = res.shareTickets
        if (shareTickets) {
          if (shareTickets.length == 0) {
            return false;
          }
          console.log("KKKKKKKKKKKKKK   转发转发转发 success 222222222")
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function (res) {

              console.log("KKKKKKKKKKKKKK   转发 get ShareInfo KKKKKKKKKKKKKKKKKKKK")

              console.log(res.encryptedData)
              console.log(res.iv)

              var encryptedData = res.encryptedData;
              var iv = res.iv;
            }
          })

        }

      },
      fail: function (res) {
        console.log("----------转发失败 fail--------------")
        console.log(res)
      }
    }


  }


})